package concurrent;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * Created by yangyang on 2017/5/25 22:12.
 * 会在运行开始抛Exception in thread "pool-1-thread-4"
 * concurrent.Pair$PairValuesNotEqualException: Pair values not equal: x: 2, y: 1
 * 之后不再抛异常，未找到原因
 */
class ExpilcitPairManager1 extends PairManager {
    // 已经给整个方法加上synchronized锁了，不明白为什么还要lock
    private Lock lock = new ReentrantLock();

    @Override
    public synchronized void increment() {
        lock.lock();
        try {
            p.incrementX();
            p.incrementY();
            store(getPair());
        }finally {
            lock.unlock();
        }
    }
}

class ExplicitPairManager2 extends PairManager {
    private Lock lock = new ReentrantLock();
    @Override
    public void increment() {
        Pair temp;
        lock.lock();
        try {
            p.incrementY();
            p.incrementX();

            temp = getPair();
        }finally {
            lock.unlock();
        }
        store(temp);
    }
}


public class ExplicitCriticalSection {
    public static void main(String[] args) {
        PairManager pm1 = new ExpilcitPairManager1(),
                pm2 = new ExplicitPairManager2();
        CriticalSection.testApproaches(pm1, pm2);
    }
}
